import axios from 'axios'
axios.defaults.timeout = 5000;
import store from '../store/index.js';
import router from "../router/index.js";
import { Toast } from 'vant';
import md5 from 'blueimp-md5'
// 请求头设置
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// 拦截器
axios.interceptors.request.use(
	config => {
		const time = Math.round(new Date().getTime()/1000).toString();
		// console.log(store.state.third_name)
		const ak = store.state.third_name
		if (config.method === 'get') {
			config.params = {
				...config.params,
				'_ak':ak,
				'_sign':md5(ak+'ZXwqGkNO8W6FtWTzABdwrhFNRVJISWEQ'+time),
				'_timestamp':time
			}
		}else if(config.method === 'post'){
			config.params = {
				'_ak':ak,
				'_sign':md5(ak+'ZXwqGkNO8W6FtWTzABdwrhFNRVJISWEQ'+time),
				'_timestamp':time
			};
		}
		return config
	},
	function(error) {
		return Promise.reject(error)
	}
)
// 响应拦截器
axios.interceptors.response.use(
    response => {
        if (response.data.code === 500 || response.data.code !== 0) {
			if(!window.location.href.includes('ceshi')){
				Toast(response.data.msg)
			}
        }
		if (response.data.code === 503) {
			Toast(response.data.msg)
			var options = {
			    errCode: 503,
			    message: '系统繁忙，请稍后'
			}
			jme.browser.showError(options);
		}
        return response
    },
    error => {
		if(error.code==='ECONNABORTED' || error.message==='Network Error' || error.message.includes('timeout')){
			Toast.fail("网络超时")
		}
        return error.response;
    }
);

//导出
export function get(url, params) {
	return new Promise((resolve, reject) => {
		axios.get(url, {
			params: params
		}).then(res => {
			resolve(res.data);
		}).catch(err => {
			reject(err.data)
		})
	});
}
export function post(url, params) {
	return new Promise((resolve, reject) => {
		axios.post(url, params)
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err.data)
			})
	});
}
